package org.origin.centre.security.token;

import org.origin.centre.security.user.XUser;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

/**
 * jwt token converter
 *
 * @author ferret
 * @version 2024-05-08
 */
@SuppressWarnings("ClassCanBeRecord")
public class JwtAuthenticationConverter implements Converter<Jwt, JwtAuthenticationToken> {
    protected final String cacheKey;
    protected final RedisTemplate<Object, Object> redisTemplate;

    public JwtAuthenticationConverter(RedisTemplate<Object, Object> redisTemplate, String cacheKey) {
        this.redisTemplate = redisTemplate;
        this.cacheKey = cacheKey;
    }

    @Override
    public JwtAuthenticationToken convert(Jwt jwt) {
        String userId = jwt.getSubject();
        Object userObject = redisTemplate.opsForValue().get(getRedisKey(userId));
        XUser userDetails = new XUser().pushMap(userObject);
        JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(jwt,
                userDetails.getAuthorities(),
                userDetails.getUsername()){
            @Override
            public Object getPrincipal() {
                return userDetails;
            }
        };
        jwtAuthenticationToken.setDetails(userDetails);
        return jwtAuthenticationToken;
    }

    public String getRedisKey(String userId) {
        return cacheKey + userId;
    }
}
